﻿namespace Api.Filters;

/// <summary>
/// 响应捕捉器
/// </summary>
public class ResponseWrapperFilter : IActionFilter, IAsyncResultFilter {
    private readonly ILogger<ResponseWrapperFilter> _logger;

    /// <summary>
    /// 响应捕捉器构造函数
    /// </summary>
    public ResponseWrapperFilter(ILogger<ResponseWrapperFilter> logger) {
        _logger = logger;
    }

    /// <summary>
    /// 响应捕捉器执行前
    /// </summary>
    public void OnActionExecuting(ActionExecutingContext context) {
    }

    /// <summary>
    /// 响应捕捉器执行后
    /// </summary>
    public void OnActionExecuted(ActionExecutedContext context) {
        if (context.Exception != null) {
            Log.WriteException(context.Exception);
            context.Result = new ObjectResult(new ResultModel {
                code = -1,
                data = context.Exception.Data,
                msg = context.Exception.Message
            });
            context.ExceptionHandled = true;
        }
    }
    /// <summary>
    /// 结果执行
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) {
        await next();
    }
}